package com.beiye.drivertransport.thematic.learning;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.SubActivity.ClipImageActivity;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.ImprovingBean;
import com.beiye.drivertransport.bean.ImprovingBeansecond;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.MineUseBean;
import com.beiye.drivertransport.bean.SexBean;
import com.beiye.drivertransport.bean.UpPhotoBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.CameraCanUseUtils;
import com.beiye.drivertransport.utils.FileUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.MessageEventPhoto;
import com.beiye.drivertransport.utils.TakePhotoDialog;
import com.beiye.drivertransport.utils.ToastUtil;
import com.beiye.drivertransport.utils.UserManger;
import com.githang.statusbar.StatusBarCompat;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//继续教育完善资料
public class ImprovingDataActivity extends TwoBaseAty {

    ImageView img_improveback;

    ImageView fgt_circleview;

    EditText ed_id;

    EditText ed_id1;

    Spinner spinner_user;

    Spinner spinner_user1;

    Spinner spinner_user2;

    TextView tv_imput;
    ArrayList<ImprovingBean> educationlist = new ArrayList<>();
    ArrayList<ImprovingBeansecond> tmolist = new ArrayList<>();
    ArrayList<SexBean> sexlist = new ArrayList<>();
    private Educationadapter educationadapter;
    private Tmoadapter tmoadapter;
    private Sexadapter sexadapter;
    //请求访问外部存储
    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 103;
    //请求写入外部存储
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;
    private File tempFile;
    private int type;
    //请求相机
    private static final int REQUEST_CAPTURE = 100;
    //请求相册
    private static final int REQUEST_PICK = 101;
    //请求截图
    private static final int REQUEST_CROP_PHOTO = 102;
    @Override
    public int getLayoutId() {
        return R.layout.activity_improving_data;
    }

    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.img_improveback) {
            finish();
        } else if (viewId == R.id.fgt_circleview) {
            if (fgt_circleview.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.mipmap.my_head).getConstantState()) {
                showTakePhotoPopupWindow();
            } else {
                SharedPreferences sp = getSharedPreferences("ImprovingDataActivity", Context.MODE_PRIVATE);
                String photoUrl = sp.getString("photoUrl", "");
                Bundle bundle = new Bundle();
                bundle.putString("photoUrl1", photoUrl);
                //startActivity(NewPhotoActivity.class, bundle);
            }
        } else if (viewId == R.id.tv_imput) {//保存
            SharedPreferences sp = getSharedPreferences("ImprovingDataActivity", Context.MODE_PRIVATE);
            String photoUrl = sp.getString("photoUrl", "");
            if (photoUrl.equals("")) {

                showToast("请您上传头像，方便课程学习时进行人脸识别");
                return;
            }

            String id = ed_id.getText().toString().trim();
            if (id.equals("")) {
                showShortToast(ImprovingDataActivity.this, "身份证不能为空");
                return;
            }
            if (!IsIDcard(id)) {
                showShortToast(ImprovingDataActivity.this, "身份证无效");
                return;
            }
            String practitionersid = ed_id1.getText().toString().trim();
            if (practitionersid.equals("")) {
                showShortToast(ImprovingDataActivity.this, "从业资格证不能为空");
                return;
            }

            String education = sp.getString("education", "");
            String tmo = sp.getString("tmo", "");
            if (tmo.equals("_请点击选择所在辖区运管所")) {
                showShortToast(ImprovingDataActivity.this, "请点击选择所在辖区运管所");
                return;
            }
            String sextype = sp.getString("sextype", "");
            LoginUserBean userInfo1 = UserManger.getUserInfo();
            LoginUserBean.DataBean data = userInfo1.getData();
            String userId = data.getUserId();
            showLoadingDialog("");
            new Login().getupdateUser(userId, id, practitionersid, sextype, education, tmo, this, 1);
        }
    }
    private void showTakePhotoPopupWindow() {

//        //设置contentView
//        final     View contentView = LayoutInflater.from(getContext()).inflate(R.layout.upphoto_popwindowlayout, null);
//        final  PopupWindow  mtakephotoPopWindow = new PopupWindow(contentView,
//                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
//
//        final      View parent = LayoutInflater.from(getContext()).inflate(R.layout.main_home_fgt, null);
//
//
//        mtakephotoPopWindow.setFocusable(false);
//        mtakephotoPopWindow.setOutsideTouchable(false);
//        parent.post(new Runnable() {
//            @Override
//            public void run() {
//                mtakephotoPopWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
//            }
//        });
//        ImageView img_takepicture =(ImageView) contentView.findViewById(R.id.img_photo2);//拍照
//        ImageView img_choosepicture =(ImageView) contentView.findViewById(R.id.img_photo1);//从相册里取
//        TextView tv_gone =(TextView) contentView.findViewById(R.id.tv_photo7);//跳过
//        img_takepicture.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                //权限判断
//                if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                        != PackageManager.PERMISSION_GRANTED) {
//                    //申请WRITE_EXTERNAL_STORAGE权限
//                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                            WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
//                } else {
//                    //跳转到调用系统相机
//                    gotoCamera();
//                }
//                mtakephotoPopWindow.dismiss();
//
//            }
//        });
//        img_choosepicture.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                //权限判断
//                if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
//                        != PackageManager.PERMISSION_GRANTED) {
//                    //申请READ_EXTERNAL_STORAGE权限
//                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
//                            READ_EXTERNAL_STORAGE_REQUEST_CODE);
//                } else {
//                    //跳转到相册
//                    gotoPhoto();
//                }
//                mtakephotoPopWindow.dismiss();
//            }
//        });
//        tv_gone.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                mtakephotoPopWindow.dismiss();
//            }
//        });

        TakePhotoDialog.Builder builder = new TakePhotoDialog.Builder(ImprovingDataActivity.this);
        builder.setTitle("为方便后台管理员审核您的继续教育");
        builder.setMessage("请上传您的个人照片");
        builder.setPositiveButton("从手机中选择照片", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //权限判断
                if (ContextCompat.checkSelfPermission(ImprovingDataActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请READ_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(ImprovingDataActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            READ_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到相册
                    gotoPhoto();
                }

                dialog.dismiss();

                //设置你的操作事项
            }
        });
        builder.setPositiveButton1("拍摄照片", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                //权限判断
                if (ContextCompat.checkSelfPermission(ImprovingDataActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(ImprovingDataActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    //跳转到调用系统相机

                    if (!CameraCanUseUtils.isCameraCanUse()) {
                        ToastUtil.showShortToast(ImprovingDataActivity.this, "请到手机设置界面里找驾运宝允许开启照相");
                        return;
                    }

                    gotoCamera();
                }
                dialog.dismiss();

                //设置你的操作事项
            }
        });
        builder.setNegativeButton("跳过", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //设置你的操作事项
            }
        });
        builder.create().show();


    }
    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if(what==1)
        {
           dismissLoadingDialog();
           showToast("保存成功");
            Intent intent = new Intent();
            // 设置回传码和Intent
            setResult(1, intent);
            finish();

        }else if(what==2)
        {
            MineUseBean mineUseBean = JSON.parseObject(result, MineUseBean.class);
            MineUseBean.DataBean data = mineUseBean.getData();
            String photoUrl = data.getPhotoUrl();
            SharedPreferences sp = getSharedPreferences("ImprovingDataActivity", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            if(photoUrl==null)
            {
                fgt_circleview.setImageResource(R.mipmap.my_head);
                editor.putString("photoUrl", "");
                editor.commit();
            }else {
                Picasso.with(ImprovingDataActivity.this).load(Uri.parse(photoUrl)).placeholder(R.mipmap.my_head).into(fgt_circleview);//加载图片
                editor.putString("photoUrl", photoUrl);
                editor.commit();
            }

        }
        super.onSuccess(result, call, response, what);
    }

    @Override
    public void onError(String result, Call call, Response response, int what) {
        if(what==1)
        {
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            String msg = checkBean.getMsg();
            dismissLoadingDialog();
            showToast(msg);
        }
        super.onError(result, call, response, what);
    }

    @Override
    public void initData() {
        img_improveback = (ImageView) findViewById(R.id.img_improveback);
        fgt_circleview = (ImageView) findViewById(R.id.fgt_circleview);
        ed_id = (EditText) findViewById(R.id.ed_id);
        ed_id1 = (EditText) findViewById(R.id.ed_id1);
        spinner_user = (Spinner) findViewById(R.id.spinner_user);
        spinner_user1 = (Spinner) findViewById(R.id.spinner_user1);
        spinner_user2 = (Spinner) findViewById(R.id.spinner_user2);
        tv_imput = (TextView) findViewById(R.id.tv_imput);

        //注册EventBus
        EventBus.getDefault().register(this);
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        // 编辑框设置触摸监听
        ed_id.setOnTouchListener(new View.OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    ed_id.setCursorVisible(true);// 再次点击显示光标
                }
                return false;
            }
        });
        // 编辑框设置触摸监听
        ed_id1.setOnTouchListener(new View.OnTouchListener() {

            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    ed_id1.setCursorVisible(true);// 再次点击显示光标
                }
                return false;
            }
        });
        ed_id.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
               ed_id1.setText(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        spinner_user.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String education = educationadapter.getItem(pos).getEducation();
                SharedPreferences sp =getSharedPreferences("ImprovingDataActivity", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("education",education);
                edit.commit();

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        spinner_user1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String tmo = tmoadapter.getItem(pos).getTmo();
                String num = tmoadapter.getItem(pos).getNum();
                SharedPreferences sp =getSharedPreferences("ImprovingDataActivity", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("tmo",num+"_"+tmo);
                edit.commit();

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        spinner_user2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String sex = sexadapter.getItem(pos).getSex();
                String sextype = sexadapter.getItem(pos).getSexType();
                SharedPreferences sp =getSharedPreferences("ImprovingDataActivity", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("sextype",sextype);
                edit.commit();

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    /**
     * 验证输入身份证号
     *
     * @param
     * @return 如果是符合格式的字符串,返回 <b>true </b>,否则为 <b>false </b>
     */
    public  boolean IsIDcard(String str) {
        String regex = "(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}[0-9Xx]$)";
        return match(regex, str);
    }
    /**
     * @param regex
     * 正则表达式字符串
     * @param str
     * 要匹配的字符串
     * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
     */
    private  boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }
    @Override
    public void requestData() {

        Bundle bundle = getIntent().getExtras();
        //通过name关键字取出用户名
        String idcNo = bundle.getString("idcNo");
       if(idcNo.equals(""))
       {
           ed_id.setText("");
           ed_id1.setText("");
       }else{
           ed_id.setText(idcNo);
           ed_id1.setText(idcNo);
       }

        Educationadapter();//学历
        TransportManagementOfficedapter();//运管所
        Sexadapter();//性别
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        String userId = data.getUserId();
        new Login().getUser(userId, this, 2);

    }



    private void Sexadapter() {
        sexlist.add(new SexBean("M","男"));
        sexlist.add(new SexBean("F","女"));
        sexadapter = new Sexadapter(ImprovingDataActivity.this,sexlist);
        spinner_user2.setAdapter(sexadapter);
        //默认选中最后一项
        spinner_user2.setSelection(0,true);
        SharedPreferences sp =getSharedPreferences("ImprovingDataActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("sextype","M");
        edit.commit();
    }

    private void TransportManagementOfficedapter() {
        tmolist.add(new ImprovingBeansecond("请点击选择所在辖区运管所",""));
        tmolist.add(new ImprovingBeansecond("江北区","2001"));
        tmolist.add(new ImprovingBeansecond("南岸区","2002"));
        tmolist.add(new ImprovingBeansecond("渝中区","2003"));
        tmolist.add(new ImprovingBeansecond("大渡口区","2004"));
        tmolist.add(new ImprovingBeansecond("沙坪坝区","2005"));
        tmolist.add(new ImprovingBeansecond("九龙坡区","2006"));
        tmolist.add(new ImprovingBeansecond("北碚区","2007"));
        tmolist.add(new ImprovingBeansecond("渝北区","2008"));
        tmolist.add(new ImprovingBeansecond("巴南区","2009"));
        tmolist.add(new ImprovingBeansecond("黔江区","2010"));
        tmolist.add(new ImprovingBeansecond("涪陵区","2011"));
        tmolist.add(new ImprovingBeansecond("万州区","2012"));
        tmolist.add(new ImprovingBeansecond("长寿区","2013"));
        tmolist.add(new ImprovingBeansecond("江津区","2014"));
        tmolist.add(new ImprovingBeansecond("合川区","2015"));
        tmolist.add(new ImprovingBeansecond("永川区","2016"));
        tmolist.add(new ImprovingBeansecond("南川区","2017"));
        tmolist.add(new ImprovingBeansecond("綦江区","2018"));
        tmolist.add(new ImprovingBeansecond("大足区","2019"));
        tmolist.add(new ImprovingBeansecond("万盛区","2020"));
        tmolist.add(new ImprovingBeansecond("北部新区","2021"));
        tmolist.add(new ImprovingBeansecond("潼南区","2022"));
        tmolist.add(new ImprovingBeansecond("铜梁区","2023"));
        tmolist.add(new ImprovingBeansecond("荣昌区","2024"));
        tmolist.add(new ImprovingBeansecond("璧山区","2025"));
        tmolist.add(new ImprovingBeansecond("梁平区","2026"));
        tmolist.add(new ImprovingBeansecond("城口县","2027"));
        tmolist.add(new ImprovingBeansecond("丰都县","2028"));
        tmolist.add(new ImprovingBeansecond("垫江县","2029"));
        tmolist.add(new ImprovingBeansecond("武隆县","2030"));
        tmolist.add(new ImprovingBeansecond("忠县","2031"));
        tmolist.add(new ImprovingBeansecond("开州区","2032"));
        tmolist.add(new ImprovingBeansecond("云阳县","2033"));
        tmolist.add(new ImprovingBeansecond("奉节县","2034"));
        tmolist.add(new ImprovingBeansecond("巫山县","2035"));
        tmolist.add(new ImprovingBeansecond("巫溪县","2036"));
        tmolist.add(new ImprovingBeansecond("石柱县","2037"));
        tmolist.add(new ImprovingBeansecond("秀山县","2038"));
        tmolist.add(new ImprovingBeansecond("酉阳县","2039"));
        tmolist.add(new ImprovingBeansecond("彭水县","2040"));
        tmolist.add(new ImprovingBeansecond("高新区","2042"));
        tmolist.add(new ImprovingBeansecond("其他","2041"));

         tmoadapter = new Tmoadapter(ImprovingDataActivity.this,tmolist);
        spinner_user1.setAdapter(tmoadapter);
        //默认选中最后一项
        spinner_user1.setSelection(0,true);
    }

    private void Educationadapter() {

        educationlist.add(new ImprovingBean("小学"));
        educationlist.add(new ImprovingBean("初中"));
        educationlist.add(new ImprovingBean("职高"));
        educationlist.add(new ImprovingBean("高中"));
        educationlist.add(new ImprovingBean("高技"));
        educationlist.add(new ImprovingBean("技校"));
        educationlist.add(new ImprovingBean("中专"));
        educationlist.add(new ImprovingBean("高职"));
        educationlist.add(new ImprovingBean("大专"));
        educationlist.add(new ImprovingBean("本科"));
        educationlist.add(new ImprovingBean("硕士"));
        educationlist.add(new ImprovingBean("博士"));


        educationadapter = new Educationadapter(ImprovingDataActivity.this,educationlist);
        spinner_user.setAdapter(educationadapter);
        //默认选中最后一项
        spinner_user.setSelection(3,true);
        SharedPreferences sp =getSharedPreferences("ImprovingDataActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("education","高中");
        edit.commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
        SharedPreferences sp =getSharedPreferences("ImprovingDataActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.clear();
        edit.commit();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEventPhoto event) {
        String message = event.getPhotourl();
        SharedPreferences sp =getSharedPreferences("ImprovingDataActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("photoUrl", message);
        editor.commit();
        Picasso.with(ImprovingDataActivity.this).load(Uri.parse(message)).placeholder(R.mipmap.my_head).into(fgt_circleview);//加载图片
        usedata();

    }
    //    class Educationadapter<ImprovingBean> extends ArrayAdapter {
//        public Educationadapter(@NonNull Context context, int resource, @NonNull List<ImprovingBean> objects) {
//            super(context, resource, objects);
//        }
//
//        @Override
//        public int getCount() {
//            //返回数据的统计数量，大于0项则减去1项，从而不显示最后一项
//            int i = super.getCount();
//            return i>0?i-1:i;
//        }
//    }
    public class Educationadapter extends BaseAdapter {
        private Context ctx;
        private LayoutInflater li;
        private ArrayList<ImprovingBean> dataList;

        public Educationadapter(Context ctx,ArrayList<ImprovingBean> dataList) {
            this.ctx = ctx;
            this.li = LayoutInflater.from(ctx);
            this.dataList = dataList;
        }

        @Override
        public int getCount() {

            return dataList.size();
        }

        @Override
        public ImprovingBean getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(ctx, R.layout.improve_item_layout, null);
                new ViewHolder(convertView);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();// get convertView's holder
            holder.tv_improve.setText(getItem(position).getEducation());
            holder.tv_improve.setGravity(Gravity.CENTER);
            return convertView;
        }

        class ViewHolder {
            TextView tv_improve;
            public ViewHolder(View convertView){
                tv_improve = (TextView) convertView.findViewById(R.id.tv_improve);
                convertView.setTag(this);//set a viewholder
            }
        }


    }
    public class Tmoadapter extends BaseAdapter {
        private Context ctx;
        private LayoutInflater li;
        private ArrayList<ImprovingBeansecond> dataList;

        public Tmoadapter(Context ctx,ArrayList<ImprovingBeansecond> dataList) {
            this.ctx = ctx;
            this.li = LayoutInflater.from(ctx);
            this.dataList = dataList;
        }

        @Override
        public int getCount() {

            return dataList.size();
        }

        @Override
        public ImprovingBeansecond getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(ctx, R.layout.improve_item_layout, null);
                new ViewHolder(convertView);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();// get convertView's holder
            holder.tv_improve.setText(getItem(position).getTmo());
            holder.tv_improve.setGravity(Gravity.CENTER);
            return convertView;
        }

        class ViewHolder {
            TextView tv_improve;
            public ViewHolder(View convertView){
                tv_improve = (TextView) convertView.findViewById(R.id.tv_improve);
                convertView.setTag(this);//set a viewholder
            }
        }


    }
    public class Sexadapter extends BaseAdapter {
        private Context ctx;
        private LayoutInflater li;
        private ArrayList<SexBean> dataList;

        public Sexadapter(Context ctx,ArrayList<SexBean> dataList) {
            this.ctx = ctx;
            this.li = LayoutInflater.from(ctx);
            this.dataList = dataList;
        }

        @Override
        public int getCount() {

            return dataList.size();
        }

        @Override
        public SexBean getItem(int position) {
            return dataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(ctx, R.layout.improve_item_layout, null);
                new ViewHolder(convertView);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();// get convertView's holder
            holder.tv_improve.setText(getItem(position).getSex());
            holder.tv_improve.setGravity(Gravity.CENTER);
            return convertView;
        }

        class ViewHolder {
            TextView tv_improve;
            public ViewHolder(View convertView){
                tv_improve = (TextView) convertView.findViewById(R.id.tv_improve);
                convertView.setTag(this);//set a viewholder
            }
        }


    }
    /**
     * 跳转到相册
     */
    private void gotoPhoto() {
        Log.d("evan", "*****************打开图库********************");
        //跳转到调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }
    /**
     * 跳转到照相机
     */
    private void gotoCamera() {
        Log.d("evan", "*****************打开相机********************");
        //创建拍照存储的图片文件
        tempFile = new File(FileUtil.checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"), System.currentTimeMillis() + ".jpg");

        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //设置7.0中共享文件，分享路径定义在xml/file_paths.xml
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(ImprovingDataActivity.this, com.beiye.drivertransport.BuildConfig.APPLICATION_ID + ".fileProvider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        startActivityForResult(intent, REQUEST_CAPTURE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == Activity.RESULT_OK) {
                    gotoClipActivity(Uri.fromFile(tempFile));
                }
                break;
            case REQUEST_PICK:  //调用系统相册返回
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = intent.getData();
                    gotoClipActivity(uri);
                }
                break;
            case REQUEST_CROP_PHOTO:  //剪切图片返回
                if (resultCode == Activity.RESULT_OK) {
                    final Uri uri = intent.getData();
                    if (uri == null) {
                        return;
                    }
                    String cropImagePath = FileUtil.getRealFilePathFromUri(ImprovingDataActivity.this, uri);
                    Bitmap bitMap = BitmapFactory.decodeFile(cropImagePath);
                    fgt_circleview.setImageBitmap(bitMap);
                    File file=new File(cropImagePath);
                    LoginUserBean userInfo = UserManger.getUserInfo();
                    LoginUserBean.DataBean data = userInfo.getData();
                    if(data==null)
                    {
                        return;
                    }
                    String userId = data.getUserId();
                    uploadImg(file,userId,bitMap);
                }
                break;
        }
    }

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();
    private void uploadImg(File mediaFile, String userId,final Bitmap bitMap) {
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        if (mediaFile != null) {
            builder.addFormDataPart("headPhoto", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
            builder.addFormDataPart("userId",userId);
        }
        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(AppInterfaceConfig.BASE_URL + "wx/uploadOfHeadPhoto")//地址
                .post(requestBody)//添加请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.e("上传失败", e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                LogUtils.e("上传成功", str);
                UpPhotoBean upPhotoBean = JSON.parseObject(str, UpPhotoBean.class);
                String data = upPhotoBean.getData();
                SharedPreferences sp = getSharedPreferences("ImprovingDataActivity", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("photoUrl", data);
                editor.commit();

                LogUtils.e("上传图片", data);
                Looper.prepare();
                   usedata();
                Looper.loop();

            }
        });

    }

    private void usedata() {
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data1 = userInfo.getData();
        String userId = data1.getUserId();
        new Login().getUser(userId, this, 2);
    }

    /**
     * 外部存储权限申请返回
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                gotoCamera();
            }
        } else if (requestCode == READ_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                gotoPhoto();
            }
        }
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(ImprovingDataActivity.this, ClipImageActivity.class);
        intent.putExtra("type", type);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }
}
